<?php

namespace Kangcg\Application\Validate\Rules;



use Kangcg\Application\Validate\Exception\RuleConfigureException;
use Kangcg\Application\Validate\Validator;

class Preg implements RuleInterface
{
    use RuleTrait;
    public $pattern = null;

    protected function afterRun(&$value, string $field, array $input, Validator $validator)
    {
        $pattern = "/{$this->pattern}/";
        if(!preg_match($pattern, $value)){
            return $validator->setError($this->getMessage($field));
        }
    }

    public function extra($extra){
        if(isset($extra['pattern'])){
            return $extra;
        }

        if(is_string($extra)){
            return [
                'pattern' => $extra
            ];
        }

        throw new RuleConfigureException("验证规则 preg 配置错误，期望【 preg => '^[\d]{1,}$' | preg => ['pattern' => '^[\d]{1,}$'] | preg => ['pattern' => '^[\d]{1,}$' 'message' => ':attribute 验证不通过']!");
    }
}
